package com.wonders.module.webservice;


import com.wonders.module.global.TradeMsg;
import com.wonders.module.mail.ws.MailService;
import com.wonders.module.utils.XMLFormatter;
import com.wondersgroup.wsscclib.xtpt.signature.KeyHelper;
import com.wondersgroup.wsscclib.xtpt.signature.SignatureHelper;
import com.wondersgroup.wsscclib.xtpt.util.ResourceHelper;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.InputStream;
import java.io.StringReader;
import java.security.PublicKey;


/**
 * 单位库 WebService 省市对接 总入口<br>
 */
@WebService
public class WsFacade {
	@SuppressWarnings("finally")
	@WebMethod(operationName = "doService", exclude = false)
	@WebResult(name = "returnVal", partName = "return")
	public byte[] doService(
			@WebParam(name = "flag", partName = "flag") byte flag,
			@WebParam(name = "xml", partName = "xml") String xml,
			@WebParam(name = "signature", partName = "signature") byte[] signature) {

		// 初始化参数
		TradeMsg tradeMsg = null;
		Object resTradeMsg = null;

		try {



			// 将xml转换成对象
			JAXBContext context = JAXBContext.newInstance(TradeMsg.class);
			Unmarshaller unmarshaller = context.createUnmarshaller();
			tradeMsg = (TradeMsg) unmarshaller.unmarshal(new StringReader(xml));

			//获取公钥验签
			InputStream pis = ResourceHelper
					.getKeyStream("I90022O9000021");
			PublicKey publicKey = KeyHelper.loadPublicKey(pis);

			if (!SignatureHelper.verify(publicKey, xml, signature)) {
				System.out.println("秘钥验证不通过");
				//					throw new LocalBusinessException(TradeCode.CODE_32, ErrorCode.VALIDATE_KEY_UNPASSED);
			}

			// 获取对象
			String busCode = tradeMsg.getHead().getBusCode();
			if (busCode.equals("sendmail"))
			{
				System.out.println("接收到的xml为"+xml);
				MailService mailService =new MailService();
				resTradeMsg = mailService.MailSend(xml);
			}
			String resxml=XMLFormatter.convertToXml(resTradeMsg);
			System.out.println("返回的xml为"+resxml);
			return XMLFormatter.getBytes(resxml);
		}
		catch (Exception e)
		{
			e.getStackTrace();
		}
		return null;
	}
}
